package com.xiyi.shouxin.dao.admin;

import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.xiyi.shouxin.dao.BaseRepository;
import com.xiyi.shouxin.dao.JdbcPreparedStatement;
import com.xiyi.shouxin.entity.admin.Admin;
import com.xiyi.shouxin.entity.admin.mapper.AdminMapper;
import com.xiyi.shouxin.exception.CommonException;
import com.xiyi.shouxin.exception.ErrorCode;

@Repository
public class AdminRepository extends BaseRepository<Admin> {

    public AdminRepository() {
        super();
        super.stat = new JdbcPreparedStatement<>(Admin.class);
    }

    public Admin findFirstByAccount(String account) throws CommonException {
        if (!StringUtils.hasText(account)) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        StringBuilder sb = new StringBuilder("SELECT ");
        sb.append(stat.GetQueryColumns());
        sb.append(" FROM ");
        sb.append(stat.GetTableName());
        sb.append(" WHERE ");
        sb.append(stat.GetColumnName("account"));
        sb.append(" = ? LIMIT 1");
        try {
            Admin admin = template.queryForObject(sb.toString(), new Object[] { account }, new AdminMapper());
            return admin;
        } catch (EmptyResultDataAccessException e) {

        }

        return null;
    }

    public List<Admin> findByMultiConditionsByPage(Long id, String keyword, Sort sort, int page, int size)
            throws Exception {
        List<Object> args = new ArrayList<>();
        List<String> conditions = new ArrayList<>();
        if (id != null) {
            conditions.add(stat.GetColumnName("id") + " = ? ");
            args.add(id);
        }
        if (StringUtils.hasText(keyword)) {
            conditions.add(stat.GetColumnName("nickName") + " LIKE ? OR " + stat.GetColumnName("account") + " LIKE ? ");
            args.add("%" + keyword + "%");
            args.add("%" + keyword + "%");
        }
        return findByMultiConditionsByPage(conditions, args, sort, page, size, new AdminMapper());
    }

    public int countByMultiConditions(Long id, String keyword) {
        List<Object> args = new ArrayList<>();
        List<String> conditions = new ArrayList<>();
        if (id != null) {
            conditions.add(stat.GetColumnName("id") + " = ? ");
            args.add(id);
        }
        if (StringUtils.hasText(keyword)) {
            conditions.add(stat.GetColumnName("nickName") + " LIKE ? OR " + stat.GetColumnName("account") + " LIKE ? ");
            args.add("%" + keyword + "%");
            args.add("%" + keyword + "%");
        }
        return countByMultiConditions(conditions, args);
    }

}
